package com.sz.sidi.oa.config;

import java.util.HashMap;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ServerHelp {
	private static ConfigurableApplicationContext ctx = null;
	
	private static Logger logger = Logger.getLogger(ServerHelp.class);

	private static HashMap<String,Object> map = new HashMap<String,Object>();
	
	private static String[] contextString = null;
	
	private ServerHelp() {}

	private static void initiaIfNeccessary() throws RuntimeException {
		if (ctx != null) {
			return;
		}

		if (contextString == null) {
			ResourceBundle res = ResourceBundle.getBundle("com.sz.sidi.oa.config.contextFiles");
			contextString = res.getString("files").split(",");
		}

		ClassLoader oldLoader = Thread.currentThread().getContextClassLoader();
		try {
			Thread.currentThread().setContextClassLoader(
					ServerHelp.class.getClassLoader());
			ctx = new ClassPathXmlApplicationContext(contextString);

		} catch (Exception e) {
			e.printStackTrace();
			logger.info(e.getLocalizedMessage());
		} finally {
			Thread.currentThread().setContextClassLoader(oldLoader);
		}
	}

	public static Object getBean(String beanId) {
		initiaIfNeccessary();
		
		Object obj = map.get(beanId);
		if(obj != null){
			return obj;
		}else{
			try{
				obj = ctx.getBean(beanId);	
			}catch(Exception e){
				e.printStackTrace();
			}
			map.put(beanId, obj);
		}
		return obj;
	}

}
